package com.yl.zqy.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.zqy.vo.common.IPageVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class QueryUtil {
    private QueryUtil() {
    }


    public static void copySpecificProperties(Object src, Object trg, Set<String> props) {
        String[] excludedProperties = Arrays.stream(BeanUtils.getPropertyDescriptors(src.getClass())).map(PropertyDescriptor::getName).filter(name -> !props.contains(name)).toArray(String[]::new);
        BeanUtils.copyProperties(src, trg, excludedProperties);
    }

    public static void copySpecificPropertiesList(List<Object> src, List<Object> trg, Set<String> props) {
        String[] excludedProperties = Arrays.stream(BeanUtils.getPropertyDescriptors(src.getClass())).map(PropertyDescriptor::getName).filter(name -> !props.contains(name)).toArray(String[]::new);

        for (Object obj : src) {
            Object temp = new Object();
            BeanUtils.copyProperties(obj, temp, excludedProperties);
            trg.add(temp);
        }
    }


    public static <T, V> IPageVo<V> iPage2IPageVo(IPage<T> oriPage) {
        IPageVo<V> iPageVo = new IPageVo<>();
        BeanUtils.copyProperties(oriPage, iPageVo);
        return iPageVo;
    }

    /**
     * 驼峰转下划线
     */
    public static String humpToUnderline(String str) {
        if (StringUtils.isEmpty(str)) return null;
        Pattern compile = Pattern.compile("[A-Z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * List转IPage
     *
     * @param list
     * @param pageNum
     * @param pageSize
     * @return
     */
    public static IPage listToPage(List list, int pageNum, int pageSize) {
        List pageList = new ArrayList<>();
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && curIdx + i < list.size(); i++) {
            pageList.add(list.get(curIdx + i));
        }
        IPage page = new Page<>(pageNum, pageSize);
        page.setRecords(pageList);
        page.setTotal(list.size());
        return page;
    }
}
